package util.psi;

import com.google.common.base.Preconditions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.PsiType;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import constant.CoreConstants;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lomoye on 2018/1/7.
 */
public class PsiClassUtil {

    /**
     * 获取包括父类的所有字段名字
     */
    public static List<String> getAllNames(PsiClass clazz) {
        List<String> allNames = new ArrayList<>();
        PsiField[] fs = clazz.getAllFields();
        for (PsiField f : fs) {
            allNames.add(f.getName());
        }

        return allNames;
    }

    public static String getSourcePath(PsiClass clazz) {
        String classPath = clazz.getContainingFile().getVirtualFile().getPath();
        return classPath.substring(0, classPath.lastIndexOf("/"));
    }

    public static PsiClass getCurrentPsiClass(AnActionEvent event) {
        PsiJavaFile javaFile = (PsiJavaFile) event.getData(PlatformDataKeys.PSI_FILE);
        Preconditions.checkArgument(javaFile != null);

        PsiClass[] classes = javaFile.getClasses();
        return classes[0];//获取到当前的class信息
    }

    public static boolean isEnum(PsiType type) {
        PsiType[] psiTypes = type.getSuperTypes();
        if (psiTypes.length != 0) {
            for (PsiType psiType : psiTypes) {
                String superName = psiType.toString();

                if (superName.contains("Enum")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String getNote(PsiField psiField) {
        PsiDocComment docComment = psiField.getDocComment();
        if (docComment == null) {
            return null;
        }
        PsiDocTag docTag = docComment.findTagByName(CoreConstants.FILED_DOC_TAG);
        if (docTag == null) {
            return null;
        }

        String note = docTag.getName();
        return note.substring(note.indexOf(":") + 1);
    }

    public static Boolean getIsNotNull(PsiField psiField) {
        PsiDocComment docComment = psiField.getDocComment();
        if (docComment == null) {
            return false;
        }
        PsiDocTag docTag = docComment.findTagByName(CoreConstants.FILED_NOT_NULL_TAG);
        return docTag != null;
    }
}
